// stagewiseCore/apps/vscode-extension/src/utils/call-qwen-agent.ts
import * as vscode from 'vscode';
import type { PromptRequest } from '@stagewise/extension-toolbar-srpc-contract';

// 全局计数器
let toolCallsSet = new Set<string>();
let fileOpsSet = new Set<string>();

export async function callQwenAgent(request: PromptRequest): Promise<void> {
  const workspaceRoot = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath;
  console.log("我看下整体路径",JSON.stringify(vscode.workspace.workspaceFolders,null,2))
  if (!workspaceRoot) {
    vscode.window.showErrorMessage('未找到工作区文件夹');
    return;
  }

  await vscode.window.withProgress({
    location: vscode.ProgressLocation.Notification,
    title: "🤖 Qwen 正在处理您的请求...",
    cancellable: true
  }, async (progress, token) => {
    
    try {
      progress.report({ increment: 10, message: "连接到 Qwen API..." });

      

      // 构建请求体
      const requestBody = {
        message: request.prompt,
        context: request.files && request.files.length > 0 ? 
          { files: request.files } : undefined,
        model: 'qwen3-coder-plus',
        tools: true,
        stream: true,
        workspaceRoots: vscode.workspace.workspaceFolders?.map(f => f.uri.fsPath) ?? []
      };

       


      console.log("我去做这个的请求处理",requestBody)

      progress.report({ increment: 20, message: "发送请求..." });

      // 调用 server.ts 的 /chat 端点
      const response = await fetch('http://localhost:3008/chat', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(requestBody),
                 signal: token.isCancellationRequested ? AbortSignal.abort() : undefined
      });

      console.log("我去做这个的相应处理",response)

      if (!response.ok) {
        throw new Error(`API 请求失败: ${response.status} ${response.statusText}`);
      }

      if (!response.body) {
        throw new Error('响应体为空');
      }

      progress.report({ increment: 30, message: "处理响应流..." });

      // 处理 SSE 流
      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      
      let responseText = '';
      let toolCallCount = 0;
      let fileOpsCount = 0;
      let sessionId = '';

      try {
        while (true) {
          if (token.isCancellationRequested) {
            reader.cancel();
            break;
          }

          const { done, value } = await reader.read();
          
          if (done) {
            break;
          }

          const chunk = decoder.decode(value, { stream: true });
          const lines = chunk.split('\n');

          for (const line of lines) {
            if (line.startsWith('event: ')) {
              const eventType = line.slice(7).trim();
              continue;
            }
            if (line.startsWith('data: ')) {
              try {
                const data = JSON.parse(line.slice(6));
                console.log('收到 SSE 事件:', data);
                await handleSSEEvent(data, progress, (text) => {
                  responseText += text;
                }, (count) => {
                  toolCallCount = count;
                }, (count) => {
                  fileOpsCount = count;
                }, (id) => {
                  sessionId = id;
                });
              } catch (parseError) {
                console.warn('解析 SSE 数据失败:', parseError, '原始行:', line);
              }
            }
          }
        }
      } finally {
        reader.releaseLock();
      }

      progress.report({ increment: 100, message: "完成!" });

      // 显示结果
      vscode.window.showInformationMessage(
        `✅ Qwen 处理完成！${toolCallCount > 0 ? `执行了 ${toolCallCount} 个操作` : ''}${fileOpsCount > 0 ? `，修改了 ${fileOpsCount} 个文件` : ''}`
      );
      
      if (responseText) {
        vscode.window.showInformationMessage(
          `💬 AI 说明: ${responseText.substring(0, 200)}${responseText.length > 200 ? '...' : ''}`,
          { modal: false }
        );
      }
      
      // 刷新文件资源管理器
      vscode.commands.executeCommand('workbench.files.action.refreshFilesExplorer');

    } catch (error: any) {
      console.error('Qwen Agent 错误:', error);
      
      if (error.name === 'AbortError' || token.isCancellationRequested) {
        vscode.window.showInformationMessage('❌ 请求已取消');
      } else if (error.message.includes('ECONNREFUSED') || error.message.includes('fetch')) {
        vscode.window.showErrorMessage(
          '❌ 无法连接到 Qwen API 服务器，请确保服务器正在运行 (http://localhost:3000)'
        );
      } else {
        vscode.window.showErrorMessage(
          `❌ Qwen 处理失败: ${error.message || '未知错误'}`
        );
      }
    }
  });
}

// 处理服务器发送的事件
async function handleSSEEvent(
  data: any, 
  progress: vscode.Progress<{ message?: string; increment?: number }>,
  onContent: (text: string) => void,
  onToolCallCount: (count: number) => void,
  onFileOpsCount: (count: number) => void,
  onSessionId: (id: string) => void
): Promise<void> {
  if (!data || typeof data !== 'object') return;

  // 处理会话信息
  if (data.sessionId) {
    onSessionId(data.sessionId);
    console.log('会话 ID:', data.sessionId);
  }

  // 处理内容事件 (基于 server.ts 的 sendSSEMessage 格式)
  if (data.data && typeof data.data === 'string') {
    onContent(data.data);
    progress.report({ message: `💬 AI 回复中...` });
  }

  // 处理工具调用请求
  if (data.data && data.data.name) {
    const toolName = data.data.name;
    progress.report({ message: `🔧 执行工具: ${toolName}` });
    
    // 统计工具调用
    toolCallsSet.add(data.data.callId || `${toolName}-${Date.now()}`);
    onToolCallCount(toolCallsSet.size);
    
    // 统计文件操作工具
    if (['write_file', 'edit_file', 'read_file', 'create_file', 'str_replace_editor'].includes(toolName)) {
      fileOpsSet.add(data.data.callId || `${toolName}-${Date.now()}`);
      onFileOpsCount(fileOpsSet.size);
    }
  }

  // 处理工具调用完成
  if (data.result) {
    progress.report({ message: `✅ 工具执行完成` });
  }

  // 处理错误事件
  if (data.error || data.message) {
    console.error('AI 处理错误:', data);
    vscode.window.showWarningMessage(`⚠️ ${data.error || data.message}`);
  }

  // 处理完成事件
  if (data.timestamp && !data.data && !data.error) {
    progress.report({ message: `✨ 处理完成` });
  }
}